<?php

trait salesTrait{

    // 加入排程
    function joinPmc($itab, $pidx, $custNo, $cordNo, $inbuz){
        global $_cbase; $db = db('erp');
        $date1 = uval('date1'); $date2 = uval('date2'); // $ord_atime = uval('ord_atime'); `下单时间`,  '$idt1', 
        $atime = date('Y-m-d H:i'); $auser=$_cbase['urow']['mname']; $aip = Basic::envIP();
        $lists = data('order_item', "`kid` IN ('$itab') AND pid='$pidx'", 99, '' , 'erp'); 
        $res = []; $cnt = 0; 
        foreach($lists as $dr){
            $kid = bozErp::kidTDB('pmc_order', '', '', 3); $pid = $dr['kid']; 
            $idt1 = empty($date1[$pid]) ? date('Y-m-d')                 : $date1[$pid];
            $idt2 = empty($date2[$pid]) ? date('Y-m-d',time()+15*86400) : $date2[$pid];
            $row = Dbop::data('pmc_order', "`pid`='$pid'", '1', '', 'erp');
            if(!empty($row)){ continue; } $cnt++; // 发货日期,出图日期,客户回签,提前天数     
            $fid1 = "  kid,    pid,    inbuz,    custNo,    cordNo,       bomNo,        bozNo";
            $val1 = "'$kid', '$pid', '$inbuz', '$custNo', '$cordNo', '$dr[bomNo]', '$dr[bozNo]'";
            $fids = "$fid1, `订单数量`,  `下单时间`,  `客户交期`,     `附件地址`,  `act`,     `inRem`,        `机型特性`,  `opBom`, `opMB`, `opElse`";
            $vals = "$val1, '$dr[数量]', '$idt1',    '$idt2',   '$dr[附件地址]',  'order', '$dr[inRem]', '$dr[机型特性]',     'X',    'X-X',  'X-X-X'";
            $sql2 = "INSERT INTO {pmc_order} ($fids,atime,auser,aip) VALUES ($vals,'$atime','$auser','$aip') ";
            $res[] = $db->run($sql2, []); //echo $sqldo;
        }
        $res['cnt'] = $cnt;
        return $res;
    }
   
    # DEEL:ID重复 // offer_main + order_main
    function getO2ids($sec='offer'){ //
        $cd1 = bozErp::kidTDB('offer_main', "", "D", 4); // 2023-0819-0001
        $cd2 = bozErp::kidTDB('order_main', "", "D", 4);
        $idA = max(substr($cd1,-3),substr($cd2,-3)); 
        //
        $no1 = bozErp::kidTDB('order_main','BZBJ','D8',3,'cordNo'); // BZBJ-20230818-002
        $no2 = bozErp::kidTDB('order_main','BZXS','D8',3,'cordNo'); // BZXS-20230818-002
        $idB = max(substr($cd1,-3),substr($cd2,-3)); 
        //
        $idX = max($idA, $idB);
        $res['cdx']    = $cdx    = substr($sec=='offer'?$cd1:$cd2,0,11) . $idX; 
        $res['cordNo'] = $cordNo = substr($sec=='offer'?$no1:$no2,0,14) . $idX; 
        return $res;
    }

    function updPinfo($pid, $sec='offer', $act=''){ // rechk, del
        $db = db('erp'); global $_cbase;
        if($act=='del'){
            $rp = data("{$sec}_item", "pid='$pid'", '1', '' , 'erp');
            if(empty($rp)){ 
                $rdel = $db->run("DELETE FROM {{$sec}_main} WHERE `kid`='$pid'", []); 
                return $rdel; // TODO
            }
        }
        $rechk = $act=='rechk' ? "act='add'," : '';
        $sql1 = "SELECT SUM(`物流费`) AS feeT, SUM(`含税总价`) AS feePA1 FROM {{$sec}_item} WHERE pid='$pid'";
        $sum = $db->get($sql1, [], '1'); $sumFee = round($sum['feePA1'],2); 
        $atime = date('Y-m-d H:i'); $auser=$_cbase['urow']['mname']; $aip = Basic::envIP();
        $sqlog = "{$rechk} exFee='$sum[feeT]',`合计金额`='$sumFee',etime='$atime',euser='$auser',eip='$aip'";
        $sqldo = "UPDATE {{$sec}_main} SET $sqlog WHERE `kid`='$pid'"; 
        return $db->run($sqldo, []);
    }
    function updPmcit($kid, $act=''){ // cancel,stop,del,del
        $db = db('erp'); global $_cbase;
        $atime = date('Y-m-d H:i'); $auser=$_cbase['urow']['mname']; $aip = Basic::envIP();
        if(strpos("(add,cancel,stop,del)",$act)>0){ 
            $sqldo = "UPDATE {pmc_order} SET act='$act',etime='$atime',euser='$auser',eip='$aip' WHERE `pid`='$kid'"; 
            return $db->run($sqldo, []);     
        }
        return [];
    }

    static function getSkipids($lists=[], $sec='offer', $act='add'){
        if(empty($lists)){ return $lists; }
        $idtb = array_column($lists, 'pid'); 
        $ids = empty($idtb) ? '(null)' : implode("','", $idtb); 
        $data = Dbop::data("{$sec}_item", "`pid` IN ('$ids') AND act='$act'", '999', '', ['dbk'=>'erp','fields'=>"pid"]);
        $idtb = array_column($data, 'pid'); 
        return empty($idtb) ? '(null)' : '(,'.implode(",", $idtb).',)'; 
    }

    // 通过pid得到主订单信息(pinifo)
    static function getPinfo($lists=[], $sec='offer'){
        if(empty($lists)){ return $lists; }
        $idtb = array_column($lists, 'pid'); 
        $ids = empty($idtb) ? '(null)' : implode("','", $idtb); 
        $fields = "kid,`cordNo`,`custNo`,act,reRem,atime,auser,aip";
        $data = Dbop::data("{$sec}_main", "`kid` IN ('$ids')", '999', '', ['dbk'=>'erp','fields'=>$fields]);
        $res1 = []; 
        foreach($data as $dr){
            $res1[$dr['kid']] = $dr;
        }
        foreach($lists as &$dr){
            $pid = $dr['pid'];
            if(isset($res1[$pid])){ 
                $dr['_pit'] = $res1[$pid];
            }else{
                $dr['_pit'] = ['kid'=>'','cordNo'=>'','custNo'=>'','act'=>'','reRem'=>'','atime'=>'','auser'=>''];
            }
        }
        return $lists;
    }

    // 导出Order(Sales)到Xls
    static function exordXls($kid, $refp=1){
        global $_cbase; $db = db('erp'); $auser = $_cbase['urow']['mname'];
        $data['mode'] = $mode = uval('mode'); 
        $mdtab = $mode=='offer' ? 'offer' : 'order';
        $data['cdx'] = $cdx = $_cbase['mkvs']['view'];
        $row = data($mdtab.'_main', "kid='$cdx'", '1', '' , 'erp');
        $lists = data($mdtab.'_item', "pid='$cdx'", '999', 'pno' , 'erp');
        $cuInfo = data('cust_main', "`编码`='$row[custNo]'", '1', '' , 'erp');
        $shcfg = bozErp::bzcfg('Share'); $coInfo = $shcfg['corpInfo']; 
        //
        $sHead  = bozErp::bzutf8('/xlstpl/OffV3-Head');
        $sRow1  = bozErp::bzutf8('/xlstpl/OffV3-Row1');
        $sRow2  = bozErp::bzutf8('/xlstpl/OffV3-Row2');
        $sNull = bozErp::bzutf8('/xlstpl/OffV3-RowNull');
        $sFoot1  = bozErp::bzutf8('/xlstpl/OffV3-Foot1');
        $sFoot2  = bozErp::bzutf8('/xlstpl/OffV3-Foot2');
        $sDoc  = bozErp::bzxmfr("OffV3", 0); //dump($row); 
        // 
        $sHead = str_replace("{custName}", $cuInfo['名称'],     $sHead);
        $sHead = str_replace("{coName}",   $coInfo['coName'],   $sHead);
        $sHead = str_replace("{custAddr}", $cuInfo['coAddr'],   $sHead);
        $sHead = str_replace("{coTel}",    $coInfo['coTel'],    $sHead);
        $sHead = str_replace("{custLink}", $cuInfo['coLink'],   $sHead);
        $sHead = str_replace("{coLink}",   $row['业务员'],      $sHead);
        $tbh = explode(",","cordNo,atime,业务员"); // custNo,
        foreach($tbh as $tk){ $sHead = str_replace("{{$tk}}", "$row[$tk]", $sHead); }    
        $sHead = str_replace("{x2Title}", $mode=='offer'?"报 价 单":"销售订单", $sHead);
        // 
        $strRows = ''; $ron = 1;
        foreach($lists as $i=>$itm){
            $istr = $i ? $sRow2 : $sRow1; //  ' 不准确？
            $teckp = preg_replace("/([2|3|4|5|6]{1})\. /", '&#10;${1}. ', $itm['技术参数']);
            $pack = $itm['包装方式']=='carton' ? '纸箱' : ($itm['包装方式']=='wooden' ? '木箱' : '(未知)');
            $istr = str_replace("{No1}", ($ron), $istr);
            $istr = str_replace("{Name1}", $itm['名称'], $istr);
            $istr = str_replace("{Packge}", $pack.'包装', $istr);
            $istr = str_replace("{Code1}", $itm['bomNo'], $istr);
            $istr = str_replace("{Code2}", $itm['bozNo'], $istr);
            $istr = str_replace("{Unit}", $itm['单位'], $istr);
            $istr = str_replace("{Num}",  $itm['数量'], $istr);
            $istr = str_replace("{Cell1}", $itm['未税单价'], $istr);
            $istr = str_replace("{Cell2}", $itm['含税单价'], $istr);
            $istr = str_replace("{Cell5}", $itm['含税总价'], $istr);
            $istr = str_replace("{Day}", $itm['交期'], $istr);
            $istr = str_replace("{Rem1}", $teckp, $istr);
            $strRows .= $istr; $ron++;
        } 
        //
        if(count($lists)<3){
            for($i=0;$i<3-count($lists);$i++){
                $strRows .= str_replace('{No1}', ($i+4), $sNull);
            }
        }
        $sFoot12 = $mode=='order' ? $sFoot2 : $sFoot1; 
        $sDoc = str_replace(["{SumNum}"], $row['合计金额'], $sDoc); // v合计金额 "{SumBig}",
        $sDoc = str_replace(["{SumBig}"], extConv::rmbText($row['合计金额']), $sDoc); // v合计金额 "{SumBig}",
        $sDoc = str_replace("{SheetRows}", 1+substr_count("$sDoc.$sHead.$strRows.$sFoot12",'</Row>'), $sDoc);
        $sDoc = str_replace("{SheetName}", "Sheet1", $sDoc);
        $sDoc = str_replace("<!--{RowHead}-->", $sHead, $sDoc);
        $sDoc = str_replace("<!--{RowData}-->", $strRows, $sDoc); 
        $sDoc = str_replace("<!--{RowFoot12}-->", $sFoot12, $sDoc); 
        //
        if($refp){
            $svfp = "/temp/Order-($row[kid])-" . Basic::kidRand('24', 4) . ".xls";
            $svre = Fsop::put(DIR_DATA . $svfp, $sDoc);
            return ['svfp'=>$svfp, 'svre'=>$svre, 'svfull'=>PATH_DATA.$svfp];
        }else{
            return ['data'=>$sDoc];
        }
    }
    
    // 定制附件归档: /erpData/Offer/2023-08/0818-B1019XH/xxx.rar
    function moveAttfp(&$fm, $custNo='', $fpid='附件地址'){
        global $_cbase; 
        if(empty($fm[$fpid])){ return; }
        if(!$custNo && !empty($fm['custNo'])){ $custNo=$fm['custNo']; }
        if(!$custNo){ $custNo='0000XXX'; }
        $attfp = $fm[$fpid];
        if(substr($attfp,0,11)=='/data/temp/'){
            $dir0 = $_cbase['udir']['erpDt']; // `E:/BozRD/erpData`
            $path0 = 'Offer';
            $pym = date('Y-m');             $path1 = "$path0/$pym";
            $pcno = date('md').'-'.$custNo; $path2 = "$path0/$pym/$pcno";
            $bsnm = basename($attfp);
            if(!is_dir("$dir0/$path1")){ mkdir("$dir0/$path1"); }
            if(!is_dir("$dir0/$path2")){ mkdir("$dir0/$path2"); }
            if(file_exists("$dir0/$path2/$bsnm")){ $bsnm = str_replace('.','-'.Basic::kidRand('f',3).'.',$bsnm); }
            @copy(DIR_DATA.substr($attfp,5), "$dir0/$path2/$bsnm");
            $fm[$fpid] = $attfp = str_replace('/data/temp/', "/erpData/$path2/", $attfp);
        }
        return $attfp;
    }

    # 物流费 相关Func =========================================================

    // 包装费 $type=carton/wooden
    static function feePack($pid, $parPack, $type=''){ 
        $vol = bozBom::getSqm($pid, $parPack);
        $shcfg = bozErp::bzcfg('Share'); 
        $pack0 = $shcfg['offSets']['pack0']; 
        $ch1 = empty($type) ? '0' : substr($type,0,1);
        $tpk = "pack$ch1"; // "pack0"=>"100",  "packc"=>"80",  "packw"=>"120", 
        if(empty($shcfg['offSets'][$tpk])){ return $pack0; }
        //echo "$vol, $pack0, $ch1, $tpk, $packx"; 
        return $vol * $shcfg['offSets'][$tpk];
    }

    // 数量折扣 ['100-51'=>0.8, '50-21'=>0.85, '20-11'=>0.9, '10-6'=>0.95, '5-1'=>1, ]  #  rateNmin"=>0.8,  "rateNmax"=>1
    static function rateNum($num=1){
        $shcfg = bozErp::bzcfg('Share'); 
        $rates = $shcfg['offSets']['rateNums']; 
        foreach($rates as $rk=>$rate){
            $tmp = explode('-', $rk);
            $n2 = intval($tmp[0]); $n1 = intval($tmp[1]);
            if($num>=$n1 && $num<=$n2){ return $rate; }
        }
        $rateNmin = $shcfg['offSets']['rateNmin']; 
        $rateNmax = $shcfg['offSets']['rateNmax']; 
        if($num>100){ return $rateNmin; }
        else{ return $rateNmax; }
    }

    // 等级折扣 ['A'=>0.8, 'B'=>0.85, 'C'=>0.9, 'D'=>0.95, 'E'=>0.98, 'F'=>1], "rateGDef"=>1,  
    static function rateGrade($grade='C'){
        $shcfg = bozErp::bzcfg('Share'); 
        $rates = $shcfg['offSets']['rateGrade']; 
        foreach($rates as $rk=>$rate){
            if($grade==$rk){ return $rate; }
        }
        $rateDef = $shcfg['offSets']['rateGDef']; 
        return $rateDef;
    }

}

/*

*/
